<?php

namespace App\Admin\Forms;

use App\Admin\Renderable\GoodsRenderable;
use App\Models\SwtGood;
use App\Models\SwtMerchant;
use App\Models\SwtMerchantMachine;
use App\Models\SwtReplenish;
use App\Models\SwtReplenishGoods;
use App\Services\AdminService;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Illuminate\Support\Facades\DB;

class ReplenishForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {

        Db::beginTransaction();
        try {

            $amount = 0;

            foreach($input['goods_list'] as $v) {
                $amount += $v['cost_price'] * $v['goods_num'];
            }

            $replenish_data = [
                'machine_id'    => $input['machine_id'],
                'amount'        => $amount,
            ];

            $deposit = SwtMerchantMachine::where('machine_id', $input['machine_id']) -> where('is_owner', 1) -> first();

            if($deposit) {
                $replenish_data['merchant_id'] = $deposit['merchant_id'];
            }


            $replenish_id = SwtReplenish::create($replenish_data) -> id;

            if(!$replenish_id) {
                throw new \Exception('补货记录新增失败');
            }

            $replenish_goods_data = [];

            foreach($input['goods_list'] as $v) {
                $replenish_goods_data[] = [
                    'replenish_id'  => $replenish_id,
                    'goods_id'      => $v['goods_id'],
                    'goods_name'    => $v['goods_name'],
                    'cost_price'    => $v['cost_price'],
                    'replenish_num' => $v['goods_num'],
                    'created_at'    => date('Y-m-d H:i:s', time())
                ];
            }

            $res = SwtReplenishGoods::insert($replenish_goods_data);

            if(!$res) {
                throw new \Exception('补货商品修改失败');
            }

            if($deposit) {
                $merchant_info = SwtMerchant::where('id', $deposit['merchant_id']) -> first();

                if(!$merchant_info) {
                    throw new \Exception('未找到用户信息');
                }
                if($amount > 0) {
                    if($deposit -> deposit_now - $amount < 0) {
                        throw new \Exception('货款不足');
                    }
                } else {
                    if($deposit -> deposit_now - $amount > $merchant_info -> deposit) {
                        throw new \Exception('超出货款');
                    }
                }

                $res = SwtMerchantMachine::where('id', $deposit -> id)->decrement('deposit_now', $amount);

                if(!$res) {
                    throw new \Exception('货款修改失败');
                }

                if($merchant_info -> shop_user_id) {
                    $params = $input;

                    $params['amount'] = $amount;

                    $params['shop_user_id'] = $merchant_info -> shop_user_id;

                    $params['type'] = $amount < 0 ? 0 : 1;

                    $res = AdminService::setDeviceDeposit($params);

                    if(!$res) {
                        throw new \Exception('同步货款失败');
                    }
                }
            }

            Db::commit();
            return $this->response()->success('操作成功')->refresh();
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->response()->error($e->getMessage());
        }
    }


    public function form()
    {
        $id = $this->payload['id'] ?? null;

        $this -> disableResetButton();

        $this -> hidden('machine_id') -> default($id);

        $this -> hidden('amount');

        $this -> table('goods_list','', function(Form $form) {
            $form -> selectTable('goods_id','商品')
                -> title('商品表')
                -> from(GoodsRenderable::make())
                -> rules('required', [ 'required' => '商品名不能为空' ])
                -> options(function ($v) {
                    if (! $v) {
                        return [];
                    }
                    return SwtGood::find($v)->pluck('goods_name_cost_price', 'id');
                })
                -> pluck('goods_name_cost_price')
                -> required();

            $form -> text('goods_num','数量')
                -> type('number')
                -> rules('required', [ 'required' => '数量不能为空'])
                -> required();

        }) -> saving(function ($data) {
            if(count($data) <= 0) {
                return $this->response()->error('补货商品不能为空');
            }

            $list = [];

            foreach($data as $v) {
                $goods_info = SwtGood::find($v['goods_id']);

                $v['cost_price'] = $goods_info -> cost_price / 1000;
                $v['goods_name'] = $goods_info -> goods_name;

                if(key_exists($v['goods_id'],$list)) {
                    $list[$v['goods_id']]['goods_num'] += $v['goods_num'];
                } else {
                    $list[$v['goods_id']] = $v;
                }
            }

            return array_merge($list);
        });
    }
}
